<!--
 * @Description: 预调整
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2021-12-29 17:29:14
 * @LastEditTime: 2023-06-22 17:24:16
 * @FilePath: \cscec-pms-admin\src\views\construction\monthPlanAdjust\components\PresetAdjust.vue
-->
<template>
  <div class="preset-adjust">
    <title-name :title="option.title" />
    <a-spin
      :spinning="loading"
    >
      <div class="btn-wrapper">
        <template v-if="!isAudit">
          <!-- <a-button
            type="primary"
            :disabled="notSelectRow || selectRow.nodeType===1 || isDetail || isOperation"
          >
            导入Project
          </a-button>
          <a-button
            type="primary"
            :disabled="notSelectRow || selectRow.nodeType===1 || isDetail || isOperation"
          >
            导出Project
          </a-button> -->
          <a-button
            type="primary"
            :disabled="notSelectRow || selectRow.nodeType===1 || isDetail || isOperation"
            @click="handleCreateSiblingWorkPack"
          >
            新增同级阶段/类别
          </a-button>
          <a-button
            type="primary"
            :disabled="notSelectRow || selectRow.nodeType === 1 || isDetail || isOperation"
            @click="handleCreateWorkPack"
          >
            新增下级阶段/类别
          </a-button>
          <a-button
            type="primary"
            :disabled="notSelectRow || isDetail || isOperation"
            @click="handleCreateWork"
          >
            新增业务事项
          </a-button>
          <a-button
            type="primary"
            :disabled="notSelectRow || selectRow.nodeOrder === 0 || selectRow.nodeOrder === 2 || selectRow.notDeleteOrUpdate || isDetail || isOperation"
            @click="handleMoveUp"
          >
            上移
          </a-button>
          <a-button
            type="primary"
            :disabled="notSelectRow || selectRow.nodeOrder === 1 || selectRow.nodeOrder === 2 || selectRow.notDeleteOrUpdate || isDetail || isOperation"
            @click="handleMoveDown"
          >
            下移
          </a-button>
          <!-- <a-button
            type="primary"
            :disabled="notSelectRow || selectRow.level === 1 || selectRow.nodeType === 1 || selectRow.notDeleteOrUpdate || isDetail || isOperation"
            @click="handleUpgradeWorkPack"
          >
            升级
          </a-button>
          <a-button
            type="primary"
            :disabled="notSelectRow || selectRow.nodeOrder === 0 || selectRow.nodeOrder === 2 || selectRow.nodeType === 1 || selectRow.notDeleteOrUpdate || isDetail || isOperation"
            @click="handleDowngradeWorkPack"
          >
            降级
          </a-button> -->
          <a-button
            type="primary"
            :disabled="notSelectRow || isDetail || isOperation || selectRow.notDeleteOrUpdate || workDisabled"
            @click="handleOperation('edit')"
          >
            信息调整
          </a-button>
          <a-button
            type="primary"
            :disabled="notSelectRow || isDetail || selectRow.isRootOneNode || isOperation ||selectRow.nodeStatus === 2 || selectRow.nodeStatus === 4 || selectRow.nodeStatus === 5 || canDelete"
            @click="handleOperation('delete')"
          >
            删除
          </a-button>
        </template>
        <a-button
          :disabled="isOperation"
          type="primary"
          @click="$refs.table.setAllTreeExpansion()"
        >
          展开全部
        </a-button>
        <a-button
          :disabled="isOperation"
          type="primary"
          @click="$refs.table.clearTreeExpand()"
        >
          收起全部
        </a-button>
        <a-button
          type="primary"
          :disabled="loading"
          @click="handleRefresh"
        >
          手动刷新
        </a-button>
      </div>
      <div class="pub-table-select-count">
        <a-icon
          type="info-circle"
          theme="twoTone"
        />
        <span>
          项目：
          <span class="totalNum">{{ tableInfo.projectName }}</span>
        </span>
        <span>
          预调整节点共
          <span class="totalNum">{{ tableInfo.totalNodeNum }}</span> 项
        </span>
        <span>
          预调整一级节点共
          <span
            class="totalNum"
            @click="handleNodeInfo(1)"
          >{{ tableInfo.firstNodeNum }}</span> 项
        </span>
        <span>
          预调整二级节点共
          <span
            class="totalNum"
            @click="handleNodeInfo(2)"
          >{{ tableInfo.secondNodeNum }}</span> 项
        </span>
        <span>
          预调整三级节点共
          <span
            class="totalNum"
            @click="handleNodeInfo(3)"
          >{{ tableInfo.threeNodeNum }}</span> 项
        </span>
      </div>
      <u-table
        ref="table"
        fixed-columns-roll
        :height="500"
        show-header-overflow
        :tree-config="{
          children: 'childTree',
          expandAll: false,
        }"
        row-id="id"
        row-key="id"
        :use-virtual="true"
        :current-row-key="currentRowKey"
        border
        class="construction-schedule-view-table"
        @row-click="handleRowClick"
      >
        <u-table-column
          v-for="item in columns1"
          :key="item.dataIndex"
          :prop="item.dataIndex"
          :label="item.title"
          :width="item.width"
          :tree-node="item.dataIndex === 'phaseCategory'"
          align="center"
        >
          <template v-slot="{ row }">
            <!-- 编辑 -->
            <span
              v-if="row.operation === 'edit'"
              :title="item.dataIndex === 'directResPerList' && row.nodeType ===1?row[item.dataIndex].map(el=>el.label).join(','):row[item.dataIndex]"
            >
              <!-- 阶段/类别类型 -->
              <span
                v-if="row.nodeType === 0"
                class="span-ellipsis"
              >
                <!-- 序号 -->
                <span v-if="item.dataIndex === 'sortNum'">
                  <img
                    v-if="row.flag"
                    :src="flag"
                    width="20"
                    hight="20"
                  >
                  <span>{{ row[item.dataIndex] }}</span>
                </span>
                <!-- 序号 -->
                <!-- 阶段类别 -->
                <BaseInput
                  v-if="item.dataIndex === 'phaseCategory'"
                  v-model="row.phaseCategory"
                  :placeholder="'请输入'+item.title"
                />
                <!-- 阶段类别 -->
                <span v-if="['businessMatters','period','planStartTime','planEndTime','adjustCase'].includes(item.dataIndex)">
                  {{ row[item.dataIndex] }}
                </span>
                <template v-if="item.dataIndex === 'controlLevelId'">
                  {{ row.controlLevelName }}
                </template>
              </span>
              <!-- 阶段/类别类型 -->
              <!-- 业务事项类型 -->
              <template v-else>
                <!-- 序号 -->
                <span
                  v-if="item.dataIndex === 'sortNum'"
                  :class="'class-'+row.statusLights"
                  class="sort-num"
                >
                  <img
                    v-if="row.flag"
                    :src="flag"
                    width="20"
                    hight="20"
                  >
                  <img
                    v-if="row.promptLights === 1 || row.promptLights === 2"
                    :src="row.promptLights === 1 ? yellowLight : redLight"
                    width="20"
                    hight="20"
                  >
                  <span>{{ row[item.dataIndex] }}</span>
                </span>
                <!-- 序号 -->
                <!-- 业务事项 -->
                <span v-if="item.dataIndex === 'businessMatters'">
                  <BaseInput
                    v-if="row.nodeStatus !== 2 && row.nodeStatus !== 4 && row.nodeStatus !== 5 && row.nodeStatus !== 6"
                    v-model="row.businessMatters"
                    :placeholder="'请输入'+item.title"
                  />
                  <span v-else>{{row.businessMatters}}</span>
                </span>
                <!-- 业务事项 -->
                <!-- 管控级别 -->
                <span v-if="item.dataIndex === 'controlLevelId'">
                  <a-select
                    v-if="row.nodeStatus !== 2 && row.nodeStatus !== 4 && row.nodeStatus !== 5 && row.nodeStatus !== 6"
                    v-model="row.controlLevelId"
                    :placeholder="'请选择'+item.title"
                    class="width-100"
                  >
                    <a-select-option
                      v-for="{value,label} in controlLevelList"
                      :key="value"
                      :value="value"
                    >
                      {{ label }}
                    </a-select-option>
                  </a-select>
                  <span v-else>{{row.controlLevelName}}</span>
                </span>
                <!-- 管控级别 -->
                <!-- 周期(天) -->
                <span v-if="item.dataIndex === 'period'">
                  <!-- <BaseInputNumber
                    v-if="row.nodeStatus !== 2 && row.nodeStatus !== 4 && row.nodeStatus !== 5 && row.nodeStatus !== 6"
                    v-model="row.period"
                    :placeholder="'请输入'+item.title"
                    :min="1"
                    :max="2000"
                    :is-int="true"
                    @blur="(e)=>{handleComputePeriod(e.target._value,row,0)}"
                  /> -->
                  {{row.period}}
                </span>
                <!-- 周期(天) -->
                <!-- 计划开始时间 -->
                <span v-if="item.dataIndex === 'planStartTime'">
                  <a-date-picker
                    v-if="row.nodeStatus !== 2 && row.nodeStatus !== 4 && row.nodeStatus !== 5 && row.nodeStatus !== 6"
                    v-model="row.planStartTime"
                    :allow-clear="false"
                    :placeholder="'请输入，如2023-01-01'"
                    :open="row.planStartTimeOpen"
                    :disabled-date="(current)=>{return planTimeDisabled(current,row,'start')}"
                    @openChange="(e)=>{row.planStartTimeOpen = e}"
                    @change="(e)=>{handleComputePeriod(e,row,1)}"
                  />
                  <span v-else>{{row.planStartTime}}</span>
                </span>
                <!-- 计划开始时间 -->
                <!-- 计划完成时间 -->
                <span v-if="item.dataIndex === 'planEndTime'">
                  <a-date-picker
                    v-if="row.nodeStatus !== 2 && row.nodeStatus !== 4 && row.nodeStatus !== 5 && row.nodeStatus !== 6"
                    v-model="row.planEndTime"
                    :allow-clear="false"
                    :placeholder="'请输入，如2023-01-01'"
                    :disabled-date="(current)=>{return planTimeDisabled(current,row,'end')}"
                    :open="row.planEndTimeOpen"
                    @change="(e)=>{handleComputePeriod(e,row,2)}"
                    @openChange="(e)=>{row.planEndTimeOpen = e}"
                  />
                  <span v-else>{{ row.planEndTime }}</span>
                </span>
                <!-- 计划完成时间 -->
                <!-- 实际完成时间 -->
                <span
                  v-if="item.dataIndex === 'completeTime'"
                  class="span-ellipsis"
                >
                  {{ row[item.dataIndex] }}
                </span>
                <!-- 实际完成时间 -->
                <!-- 完成标准 -->
                <span v-if="item.dataIndex === 'completeStandard'">
                  <a-auto-complete
                    v-if="row.nodeStatus !== 2 && row.nodeStatus !== 4 && row.nodeStatus !== 5 && row.nodeStatus !== 6"
                    v-model="row.completeStandard"
                    :placeholder="'请选择'+item.title"
                    :data-source="completeStandardList"
                    class="width-100"
                    allow-clear
                    :filter-option="true"
                    @change="handleCompleteStandard($event,row)"
                  />
                  <span v-else>{{row.completeStandard}}</span>
                </span>
                <!-- 完成标准 -->
                <!-- 验证资料 -->
                <span v-if="item.dataIndex === 'verifyFiles'">
                  <BaseInput
                    v-if="row.nodeStatus !== 2 && row.nodeStatus !== 4 && row.nodeStatus !== 5 && row.nodeStatus !== 6"
                    v-model="row.verifyFiles"
                    :placeholder="'请输入'+item.title"
                  />
                  <span v-else>{{row.verifyFiles}}</span>
                </span>
                <!-- 验证资料 -->
                <!-- 第一责任人 -->
                <span
                  v-if="item.dataIndex === 'firstResName'"
                  class="span-btn-ellipsis"
                >
                  <span
                    v-show="row.firstResName"
                    class="span-btn-ellipsis-text"
                  >
                    {{ row[item.dataIndex] }}
                  </span>
                  <a
                    v-if="row.nodeStatus !== 2 && row.nodeStatus !== 4 && row.nodeStatus !== 5 && row.nodeStatus !== 6"
                    class="span-btn-ellipsis-btn"
                    @click="handleFirstResNameSelect(row)"
                  > {{ row.firstResName?'(重新选择)':'选择岗位' }} </a>
                </span>
                <!-- 第一责任人 -->
                <!-- 直接责任人 -->
                <div
                  v-if="item.dataIndex === 'directResPerList'"
                  class="span-btn-ellipsis"
                >
                  <span
                    v-show="row.directResPerList && row.directResPerList.length>0 && !row.showSelect"
                    class="span-btn-ellipsis-text"
                  >
                    {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                  </span>
                  <a-select
                    v-show="row.showSelect"
                    :ref="'directSelect-' + row.sortNum"
                    v-model="row.directResPerList"
                    :placeholder="'请选择'+item.title"
                    label-in-value
                    mode="multiple"
                    class="span-btn-ellipsis-text"
                    @dropdownVisibleChange="dropdownVisibleChange($event, row)"
                    @change="((value)=>{handleDirectResPerList(value,row)})"
                  >
                    <a-select-option
                      v-for="{employeeId,name,phone} in directlyDutyPersonList"
                      :key="employeeId"
                      :value="employeeId"
                      :data="{directResPerName:name}"
                    >
                      <a-tooltip :placement="'topLeft'">
                        <template slot="title">
                          {{ phone }}
                        </template>
                        {{ name }}
                      </a-tooltip>
                    </a-select-option>
                  </a-select>
                  <a
                    v-if="row.nodeStatus !== 2 && row.nodeStatus !== 4 && row.nodeStatus !== 5 && row.nodeStatus !== 6"
                    class="span-btn-ellipsis-btn"
                    @click="handleDirectResPerSelect(row,true)"
                  >(点击选择)</a>
                </div>
                <!-- 直接责任人 -->
                <!-- 节点状态 -->
                <span
                  v-if="item.dataIndex === 'nodeStatusName'"
                  class="span-ellipsis"
                >
                  {{ row[item.dataIndex] }}
                </span>
                <!-- 节点状态 -->
                <!-- 调整情况 -->
                <span
                  v-if="item.dataIndex === 'adjustCase'"
                  class="span-ellipsis"
                >
                  {{ row[item.dataIndex] }}
                </span>
                <!-- 调整情况 -->
              </template>
              <!-- 业务事项类型 -->
            </span>
            <!-- 编辑 -->
            <!-- 查看 -->
            <span
              v-else
              :title="row[item.dataIndex]"
              class="span-ellipsis"
            >
              <template v-if="row.nodeType === 0">
                <span
                  v-if="item.dataIndex === 'sortNum'"
                  class="sort-num class-0"
                >
                  <img
                    v-if="row.flag"
                    :src="flag"
                    width="20"
                    hight="20"
                  >
                  <span>{{ row[item.dataIndex] }}</span>
                </span>
                <template v-if="['phaseCategory','businessMatters','period','planStartTime','planEndTime','adjustCase'].includes(item.dataIndex)">
                  {{ row[item.dataIndex] }}
                </template>
                <template v-if="item.dataIndex === 'controlLevelId'">
                  {{ row.controlLevelName }}
                </template>
              </template>
              <template v-else>
                <!-- 序号 -->
                <span
                  v-if="item.dataIndex === 'sortNum'"
                  :class="'class-'+row.statusLights"
                  class="sort-num"
                >
                  <img
                    v-if="row.flag"
                    :src="flag"
                    width="20"
                    hight="20"
                  >
                  <img
                    v-if="row.promptLights === 1 || row.promptLights === 2"
                    :src="row.promptLights === 1 ? yellowLight : redLight"
                    width="20"
                    hight="20"
                  >
                  <span>{{ row[item.dataIndex] }}</span>
                </span>
                <!-- 序号 -->
                <!-- 计划开始时间/计划完成时间-->
                <span v-else-if="item.dataIndex === 'planStartTime' || item.dataIndex === 'planEndTime'">
                  {{ formatDate( row[item.dataIndex],false) }}
                </span>
                <!-- 计划开始时间/计划完成时间 -->
                <template v-else-if="item.dataIndex === 'controlLevelId'">
                  {{ row.controlLevelName }}
                </template>
                <template v-else-if="item.dataIndex === 'directResPerList'">
                  {{ row[item.dataIndex].map(el=>el.label).join(',') }}
                </template>
                <template v-else>
                  {{ row[item.dataIndex] }}
                </template>
              </template>
            </span>
            <!-- 查看 -->
          </template>
        </u-table-column>
        <u-table-column
          key="operation"
          label="操作"
          width="170"
          align="center"
          fixed="right"
        >
          <template v-slot="{ row }">
            <!-- :key="row.id"避免插槽数据更新不及时 -->
            <MoreButton :key="row.id + new Date().getTime()">
              <a
                v-if="row.adjustOpt === 1 && row.operation !== 'edit' && row.operation !== 'delete'"
                @click="handleHistory(row)"
              >历史调整信息</a>
              <a
                v-if="row.operation === 'edit' && row.adjustOpt === 'ADD'"
                @click="handleConfirm(row)"
              >确认</a>
              <a
                v-if="row.operation === 'edit' && row.adjustOpt !== 'ADD'"
                @click="handleAdjust(row)"
              >确认调整</a>
              <a
                v-if="row.operation === 'delete'"
                @click="handleRemove(row)"
              >确认删除</a>
              <a
                v-if="row.operation === 'edit' || row.operation === 'delete'"
                @click="handleCancel(row)"
              >取消</a>
            </MoreButton>
          </template>
        </u-table-column>
      </u-table>
      <!-- 选择第一责任人 -->
      <modal
        v-if="firstResNameVisible"
        :id="firstResNameData.id"
        :form-data="firstResNameData.formData"
        :org-query="firstResNameData.orgQuery"
        :screening="true"
        :visible="true"
        @handleCancelFirstRes="firstResNameVisible = false"
        @handleOk="handleFirstResName"
      />
      <!-- 选择第一责任人 -->
      <!-- 历史调整信息 -->
      <HistoryAdjust
        :visible.sync="historyAdjustVisible"
        :data="historyAdjustData"
        :is-audit="isAudit"
      />
      <!-- 历史调整信息 -->
    </a-spin>
  </div>
</template>
<script>
import { getProjects } from '@/api/construction/planInput'
import { columns1, controlLevelList, completeStandardList, verifyFilesList } from '../model.js'
import { UTable, UTableColumn } from 'umy-ui'
import { view } from '@/api/construction/monthPlanAdjust'
import modal from '@/components/SelectJobs'
import Vue from 'vue'
import { getOrganizeUserListQuick } from '@/api/commons'
import HistoryAdjust from './HistoryAdjust'
// import MoreButton from '@/components/MoreButton'
export default {
  name: 'PresetAdjust' + Date.now(),
  props: {
    isAudit: {
      // 是否作为审批详情
      type: Boolean,
      default: false
    },
    // 配置项
    option: {
      type: Object,
      default: () => {
        return {
          title: '',
          businessType: 0
        }
      }
    }
  },
  components: {
    UTable,
    UTableColumn,
    modal,
    HistoryAdjust
    // MoreButton
  },
  data() {
    return {
      // 选中项
      selectRow: {},
      // 加载
      loading: false,
      // 表格信息
      tableInfo: {
        projectName: void 0,
        totalNodeNum: void 0,
        firstNodeNum: void 0,
        secondNodeNum: void 0,
        threeNodeNum: void 0,
        projectId: void 0
      },
      // 表头
      columns1,
      // 表格数据
      tableData: [],
      // 旗帜
      flag: require('@/assets/blueFlag.png'),
      // 红灯
      redLight: require('@/assets/icons/redLight.png'),
      // 黄灯
      yellowLight: require('@/assets/icons/yellowLight.png'),
      // 高亮行id
      currentRowKey: '',
      // 管控级别列表
      controlLevelList,
      // 完成标准
      completeStandardList,
      // 第一责任人模态框显示隐藏
      firstResNameVisible: false,
      // 第一责任人模态框数据
      firstResNameData: {
        id: '',
        formData: {
          fileList: []
        },
        orgQuery: {},
        row: {}
      },
      // 直接责任人列表
      directlyDutyPersonList: [],
      // 验证资料
      verifyFilesList,
      // 必填字段
      dataIndex: [
        ['phaseCategory'],
        [
          'businessMatters',
          'controlLevelId',
          'period',
          'planStartTime',
          'planEndTime',
          // 'completeDate',
          // 'frontTask',
          // 'intervalTime',
          'completeStandard',
          'verifyFiles',
          'firstResName',
          'directResPerList'
        ]
      ],
      // 历史调整信息隐藏显示
      historyAdjustVisible: false,
      // 历史调整信息数据
      historyAdjustData: {}
    }
  },
  computed: {
    // 没有选中
    notSelectRow() {
      return JSON.stringify(this.selectRow) === '{}'
    },
    // 是查看
    isDetail() {
      return this.$route.query.pageType === 'detail' || this.isAudit
    },
    // 在调整或者删除状态
    isOperation() {
      return this.selectRow?.operation === 'edit' || this.selectRow?.operation === 'delete'
    },
    // 调整id
    adjustId() {
      return this.$route.query.id ?? ''
    },
    // 业务事项 按期完成、逾期完成、审核中时不能调整
    workDisabled() {
      const nodeStatus = [2, 4, 5]
      return nodeStatus.includes(this.selectRow?.nodeStatus)
    },
    // 能否删除
    canDelete(){
      if(this.selectRow.nodeType === 0){
        // 阶段/类别
        return Array.isArray(this.selectRow.childTree) && this.selectRow.childTree.length > 0
      }else{
        // 业务事项
        return this.selectRow.notDeleteOrUpdate
      }
    }
  },
  watch: {
    // 第一责任人模态框关闭
    predecessorTaskVisible: {
      handler(newV, oldV) {
        if (!newV) {
          this.loadData()
        }
      }
    },
    // 表格数据监听
    tableData: {
      async handler(list) {
        this.currentRowKey = ''
        if (this.$refs.table) {
          this.loading =true
          const eachTree = (list) => {
            for (let i = 0; i < list.length; i++) {
              // 初始化时间弹层隐藏显示(解决时间输入识别后不能自动关闭)
              list[i].planStartTimeOpen = false
              list[i].planEndTimeOpen = false
              if (list[i].childTree) {
                eachTree(list[i].childTree)
              }
            }
          }
          eachTree(this.tableData)
          // 获取之前展开数据
          const expandRecords = this.$refs.table.getTreeExpandRecords()
          const scrollTop = this.$refs.table.tableExample().bodyWrapper.scrollTop
          const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
          // 加载数据
          await this.$refs.table.reloadData(list).then(() => {
            // 数据加载完成出现之后，打开之前的展开行
            expandRecords.forEach((row) => {
              this.$refs.table.setTreeExpansion(row, true)
            })
            // 还原之前滚动高度
            this.$refs.table.pagingScrollTopLeft(scrollTop + 1, scrollLeft)
            this.$nextTick(()=>{
              // 不加这一步，列表操作栏 会变形
              this.$refs.table.pagingScrollTopLeft(scrollTop, scrollLeft)
            })
          })
          this.currentRowKey = this.selectRow.id
          this.loading = false
        }
      },
      deep: true
    }
  },
  methods: {
    /**
     * @description: 表格行点击
     * @param {object} row 行数据
     * @param {object} column 表头对象
     * @param {event} event 事件对象
     * @return {void}
     */
    handleRowClick(row, column, event) {
      if (this.selectRow?.id !== row.id) {
        // 业务事项
        if (row.nodeType === 1) {
          this.getDirectlyDutyPerson(row)
        }
        // 改变选中项
        if (this.selectRow?.operation === 'edit') {
          // 当前已经有项正在编辑中
          this.currentRowKey = ''
          const timer = setTimeout(() => {
            this.currentRowKey = this.selectRow.id
            clearTimeout(timer)
          })
          this.$message.warning('请先保存当前预调整')
        } else if (this.selectRow?.operation === 'delete') {
          // 当前已经有项在删除中
          this.currentRowKey = ''
          const timer = setTimeout(() => {
            this.currentRowKey = this.selectRow.id
            clearTimeout(timer)
          })
          this.$message.warning('请先确认删除当前调整')
        } else {
          // 设置第一责任人信息
          this.firstResNameData.row.firstResId = row.firstResId
          this.firstResNameData.row.firstResName = row.firstResName
          // 可以改变
          this.$set(this, 'selectRow', this.$clone(row))
        }
      }
    },
    /**
     * @description: 获取直接责任人
     * @param {object} row 行数据
     * @return {void}
     */
    getDirectlyDutyPerson(row) {
      getOrganizeUserListQuick({ projectId: this.tableInfo.projectId }).then(({ code, data }) => {
        if (code === 200) {
          this.directlyDutyPersonList = data
        } else {
          this.directlyDutyPersonList = []
        }
      })
    },
    /**
     * @description: 表格数据加载方法
     * @param {boolean} isFirst 是否需要加载前置数据
     * @return {Promise} 接口Promise
     */
    async loadData(isFirst = false) {
      this.loading =true
      try {
        const {
          code,
          data: { projectName, totalNodeNum, firstNodeNum, secondNodeNum, threeNodeNum, planStartTime, planEndTime, treeListVO, projectId }
        } = await view.planAdjustDetail({
          planAdjustId: this.adjustId,
          businessType: this.option.businessType
        })
        if (code === 200) {
          this.tableInfo = {
            projectName,
            totalNodeNum,
            firstNodeNum,
            secondNodeNum,
            threeNodeNum,
            projectId
          }
          this.tableData = treeListVO
          // 设置第一责任人信息
          if (isFirst) {
            // 获取前置数据
            const orgInfo = await getProjects({ projectIds: [this.tableInfo.projectId] })
            this.firstResNameData.orgQuery.ids = orgInfo.data[0].orgId
            const userInfo = Vue.getAcloudProvider().getUserInfo()
            this.firstResNameData.id = userInfo.id
          }
        } else {
          this.tableData = []
        }
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },
    /**
     * @description: 新增同级阶段/类别
     * @param {void}
     * @return {void}
     */
    handleCreateSiblingWorkPack() {
      const vm = this
      this.$confirm({
        okText: '确定',
        cancelText: '取消',
        title: '确定新增同级阶段/类别?',
        onOk() {
          view.createSiblingWorkPack({ selectedWorkPackId: vm.selectRow.id }).then(({ code }) => {
            if (code === 200) {
              vm.$message.success('新增成功')
              vm.loadData()
            }
          })
        }
      })
    },
    /**
     * @description: 新增下级阶段/类别
     * @param {void}
     * @return {void}
     */
    handleCreateWorkPack() {
      const vm = this
      this.$confirm({
        okText: '确定',
        cancelText: '取消',
        title: '确定新增下级阶段/类别?',
        onOk() {
          vm.loading = true
          view
            .createChildWorkPack({ selectedWorkPackId: vm.selectRow.id })
            .then(({ code }) => {
              if (code === 200) {
                vm.$message.success('新增成功')
                vm.loadData()
              }
            })
            .finally(() => {
              vm.loading = false
            })
        }
      })
    },
    /**
     * @description: 新增业务事项
     * @param {void}
     * @return {void}
     */
    handleCreateWork() {
      const vm = this
      this.$confirm({
        okText: '确定',
        cancelText: '取消',
        title: '确定新增业务事项?',
        onOk() {
          vm.loading = true
          if (vm.selectRow.nodeType === 1) {
            // 新增同级业务事项
            view
              .createSiblingWork({ selectedWorkId: vm.selectRow.id })
              .then(({ code }) => {
                if (code === 200) {
                  vm.$message.success('新增成功')
                  vm.loadData()
                }
              })
              .finally(() => {
                vm.loading = false
              })
          } else {
            // 新增下级业务事项
            view
              .createChildWork({ selectedWorkPackId: vm.selectRow.id })
              .then(({ code }) => {
                if (code === 200) {
                  vm.$message.success('新增成功')
                  vm.loadData()
                }
              })
              .finally(() => {
                vm.loading = false
              })
          }
        }
      })
    },
    /**
     * @description: 上移
     * @param {void}
     * @return {void}
     */
    handleMoveUp() {
      this.loading =true
      view
        .moveUp({ selectedId: this.selectRow.id })
        .then(({ code }) => {
          if (code === 200) {
            this.$message.success('上移成功')
            this.loadData()
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * @description: 下移
     * @param {void}
     * @return {void}
     */
    handleMoveDown() {
      this.loading =true
      view
        .moveDown({ selectedId: this.selectRow.id })
        .then(({ code }) => {
          if (code === 200) {
            this.$message.success('下移成功')
            this.loadData()
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * @description: 格式化时间
     * @param {object/string} date 时间对象或字符串
     * @param {boolean} toMoment 是否转换为Moment
     * @return {object} moment时间格式
     */
    formatDate(date, toMoment = true) {
      if (date?._isAMomentObject) {
        return toMoment ? date : date.format('YYYY-MM-DD')
      } else {
        return toMoment ? this.moment(date) : date
      }
    },
    /**
     * @description: 计划开始/结束时间禁用
     * @param {object} current 当前时间对象
     * @param {object} row 行数据
     * @param {string} type 开始/结束时间(start/end)
     * @return {boolean}
     */
    planTimeDisabled(current, row, type) {
      // 开始和结束时间规则
      // 10，上月逾期、本月计划的节点的计划开始时间、节点的计划完成时间：
      // 1）若父级的阶段/类别的计划完成时间＞本月末，则本月1日≤业务事项的“计划开始时间/计划完成时间”≤本月末；
      // 2）若本月1日≤父级的阶段/类别的计划完成时间≤本月末，则本月1日≤业务事项的“计划开始时间/计划完成时间”≤父级的计划完成时间
      // 3）若父级的阶段/类别的计划完成时间＜本月1日，则本月1日≤业务事项的“计划开始时间/计划完成时间”≤本月末
      // 4）在以上基础上，计划完成时间≥计划开始时间
      // 11，在编辑下月重点计划时：
      // 1）若父级的阶段/类别的计划完成时间＞下月末，则下月1日≤业务事项的“计划开始时间/计划完成时间”≤下月末；
      // 2）若下月1日≤父级的阶段/类别的计划完成时间≤下月末，则下月1日≤业务事项的“计划开始时间/计划完成时间”≤父级的计划完成时间
      // 3）在以上基础上，计划完成时间≥计划开始时间

      // 总结规则为
      // 父节点完成时间 > 本月末
      //   本月初 <= 子节点开始/结束时间 <= 本月末
      // 本月初 <= 父节点完成时间 <= 本月末
      //   本月初 <= 子节点开始/结束时间 <= 父节点完成时间
      // 父节点完成时间 < 本月初
      //   本月初 <= 子节点开始/结束时间 <= 本月末
      // 子节点开始时间<= 子节点结束时间
      // 下月的情况 本月末替换为下月末，减少第三个条件

      // 月初
      let monthStart = this.option.businessType === 2 ? this.moment().add(1, 'month').startOf('month') : this.moment().startOf('month')
      // 月末
      let monthEnd = this.option.businessType === 2 ? this.moment().add(1, 'month').endOf('month') : this.moment().endOf('month')
      // 父节点完成时间、上月逾期时(当没有父节点完成日期时用第一种情况处理，所以设置了下下月月初,只要满足第一种情况即可)
      const ptime = row.parentCompleteTime && this.option.businessType !== 0 ? this.moment(row.parentCompleteTime).endOf('day') : this.moment().add(2, 'month').startOf('month')
      // 子节点开始时间<= 子节点结束时间(结束时间不存在时直接true)
      const se = type === 'start' ? (row.planEndTime ? current <= this.moment(row.planEndTime).endOf('day') : true) : row.planStartTime ? this.moment(row.planStartTime).startOf('day') <= current : true
      if (ptime > monthEnd || ptime < monthStart) {
        // 当 父节点完成时间 > 本月末 或 父节点完成时间 < 本月初 (即1或3的情况)
        return current && !(monthStart <= current && current <= monthEnd && se)
      } else {
        // 当 本月初 <= 父节点完成时间 <= 本月末
        return current && !(monthStart <= current && current <= ptime && se)
      }
    },
    /**
     * @description: 计算周期
     * @param {object} row 行数据
     * @param {number} index 字段索引
     * @return {void}
     */
    handleComputePeriod(value, row, index) {
      if ((value ?? '') === '') {
        if (index > 0) {
          this.$message.warning('请输入正确的日期格式，如“2023-01-01')
        }
        return false
      } else {
        const { period, planStartTime, planEndTime } = row
        // 长度不在有三个(取消周期)
        const length = [planStartTime, planEndTime].filter((el) => el ?? '' !== '').length
        // 时间周期值个等于2
        if (length === 2) {
          // 修改周期
          if (index === 0) {
            if ((period ?? '') !== '') {
              if ((planStartTime ?? '') !== '') {
                // 计算计划完成时间(三期:计划完成时间 = 计划开始时间 + (周期 - 1))
                row.planEndTime = this.formatDate(planStartTime)
                  .clone()
                  .add(period - 1, 'days')
              } else {
                // 计算计划开始时间(三期:计划开始时间 = 计划完成时间 - (周期 - 1))
                row.planStartTime = this.formatDate(planEndTime)
                  .clone()
                  .subtract(period + 1, 'days')
              }
            }
          }
          // 修改计划开始时间
          if (index === 1) {
            if ((planStartTime ?? '') !== '') {
              if ((planEndTime ?? '') !== '') {
                // 计算周期(三期:周期=(计划完成时间-计划开始时间) + 1)
                row.period = this.formatDate(planEndTime).diff(this.formatDate(planStartTime), 'days') + 1 || void 0
              } else {
                // 计算计划完成时间(三期:计划完成时间 = 计划开始时间 + (周期 - 1))
                row.planEndTime = this.formatDate(planStartTime)
                  .clone()
                  .add(period - 1, 'days')
              }
            }
          }
          // 修改计划完成时间
          if (index === 2) {
            if ((planEndTime ?? '') !== '') {
              if ((planStartTime ?? '') !== '') {
                if (this.moment(planEndTime) < this.moment(row.planStartTime).startOf('day')) {
                  this.$message.warning('计划完成时间不能早于计划开始时间')
                } else {
                  // 计算周期(三期:周期=(计划完成时间-计划开始时间) + 1)
                  row.period = this.formatDate(planEndTime).diff(this.formatDate(planStartTime), 'days') + 1 || void 0
                }
              } else {
                // 计算计划开始时间(三期:计划开始时间 = 计划完成时间 - (周期 - 1))
                row.planStartTime = this.formatDate(planEndTime)
                  .clone()
                  .subtract(period + 1, 'days')
              }
            }
          }
        }
        // 时间周期值个等于3
        if (length === 3) {
          // 修改周期或者修改计划开始时间
          if (index === 0 || index === 1) {
            // 计算计划完成时间(三期:计划完成时间 = 计划开始时间 + (周期 - 1))
            row.planEndTime = this.formatDate(planStartTime)
              .clone()
              .add(period - 1, 'days')
          }
          // 修改计划完成时间
          if (index === 2) {
            // 计算周期(三期:周期=(计划完成时间-计划开始时间) + 1)
            row.period = this.formatDate(planEndTime).diff(this.formatDate(planStartTime), 'days') + 1 || void 0
          }
        }
        // 结合open、openChange解决时间选择器不能在输入后自动关闭的问题
        if (index === 1 || index === 2 || index === 3 || index === 4) {
          row.planStartTimeOpen = false
          row.planEndTimeOpen = false
        }
      }
    },
    /**
     * @description: 选择第一责任人
     * @param {object} row 当前行数据
     * @return {void}
     */
    handleFirstResNameSelect(row) {
      this.firstResNameData.row = row
      this.firstResNameVisible = true
    },
    /**
     * @description: 选择第一责任人回调
     * @param {object} value 选中项数据
     * @return {void}
     */
    handleFirstResName(value, row) {
      this.firstResNameData.row.firstResId = value.jobsSelectedId
      this.firstResNameData.row.firstResName = value.jobsSelectedName
      this.firstResNameVisible = false
    },
    /**
     * @description: 直接责任人下拉展开收起
     * @param {boolean} visible 下拉隐藏显示
     * @param {object} row 当前行数据
     * @return {void}
     */
    dropdownVisibleChange(visible, row) {
      if (!visible) {
        this.handleDirectResPerSelect(row, false)
      }
    },
    /**
     * @description: 直接责任人改变
     * @param {object} value 选中项
     * @param {object} row 行数据
     * @return {void}
     */
    handleDirectResPerList(value, row) {
      row.directResPerList = this.directlyDutyPersonList
        .filter((item) => value.map((el) => el.key).includes(item.employeeId))
        .map((el) => {
          return {
            key: el.employeeId,
            label: el.name
          }
        })
    },
    /**
     * @description: 直接责任人选择
     * @param {object} row 行数据
     * @return {void}
     */
    handleDirectResPerSelect(row, isShow) {
      this.$set(row, 'showSelect', isShow)
      if (row.showSelect) {
        this.$refs[`directSelect-${row.sortNum}`][0].$el.click()
      }
    },
    /**
     * @description: 完成标准带出验证资料
     * @param {string} value 完成标准值
     * @param {object} row 行数据
     * @return {void}
     */
    handleCompleteStandard(value, row) {
      const index = this.completeStandardList.findIndex((el) => el === value)
      if (index >= 0) {
        row.verifyFiles = this.verifyFilesList[index]
      }
    },
    /**
     * @description: 操作行
     * @param {string} type 操作类型('edit','delete')
     * @return {void}
     */
    handleOperation(type) {
      const loop = (list, id) => {
        for (let i = 0; i < list.length; i++) {
          if (list[i].id === id) {
            list[i].operation = type
          } else {
            list[i].operation = ''
          }
          if (Array.isArray(list[i].childTree) && list[i].childTree.length > 0) {
            loop(list[i].childTree, id)
          }
        }
      }
      const list = this.$clone(this.tableData)
      loop(list, this.selectRow.id)
      this.tableData = list
      this.$set(this.selectRow, 'operation', type)
      const timer = setTimeout(() => {
        const event = new Event('scroll', { bubbles: true, cancelable: false })
        document.querySelector('.el-table__body-wrapper').dispatchEvent(event)
        clearTimeout(timer)
      }, 100)
    },
    /**
     * @description: 确认
     * @param {object} row 行数据
     * @return {object} 校验通过与否
     */
    handleConfirm(row) {
      const valid = this.verify(row)
      if (valid.pass) {
        row.operation = ''
        this.selectRow.operation = ''
        this.handleUpdate(row)
      } else {
        this.$message.warning(`${valid.dataIndex}不能为空`)
      }
    },
    /**
     * @description: 校验行
     * @param {object} row 行数据
     * @return {boolean} 是否通过{pass:true/false,dataIndex:''}
     */
    verify(row) {
      const keyList = this.dataIndex[row.nodeType]
      for (let i = 0; i < keyList.length; i++) {
        const node = row[keyList[i]] ?? ''
        if (node !== '') {
          if (Array.isArray(node)) {
            if (node.length <= 0) {
              return {
                pass: false,
                dataIndex: this.columns1.find((item) => item.dataIndex === keyList[i]).title
              }
            }
          }
        } else {
          return {
            pass: false,
            dataIndex: this.columns1.find((item) => item.dataIndex === keyList[i]).title
          }
        }
      }
      return {
        pass: true,
        dataIndex: ''
      }
    },
    /**
     * @description: 确认调整
     * @param {object} row 行数据
     * @return {void}
     */
    handleAdjust(row) {
      const valid = this.verify(row)
      if (valid.pass) {
        row.operation = ''
        this.selectRow.operation = ''
        this.handleUpdate(row)
      } else {
        this.$message.warning(`${valid.dataIndex}不能为空`)
      }
    },
    /**
     * @description: 编辑
     * @param {object} row 行数据
     * @return {void}
     */
    handleUpdate(row) {
      const fun = row.nodeType === 0 ? view.editWorkPack : view.editWork
      this.loading =true
      fun(
        Object.fromEntries(
          ['id', 'firstResId', ...this.dataIndex[row.nodeType]].map((el) => {
            if (el === 'businessMatters' || el === 'phaseCategory') {
              return ['name', row[el]]
            } else if (el === 'parentId') {
              return ['workPackId', row[el]]
            } else if (el === 'planEndTime' || el === 'planStartTime') {
              return [el, this.formatDate(row[el], false)]
            } else if (el === 'firstResId') {
              return [el, this.firstResNameData.row.firstResId]
            } else {
              return [el, row[el]]
            }
          })
        )
      )
        .then(({ code }) => {
          if (code === 200) {
            this.$message.success('编辑成功')
            this.selectRow = {}
            row.operation = ''
            this.currentRowKey = ''
            this.loadData()
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    /**
     * @description: 删除
     * @param {void}
     * @return {void}
     */
    handleRemove(row) {
      const vm = this
      if (this.selectRow.nodeType === 0) {
        // 删除阶段/类别
        this.$confirm({
          okText: '确定',
          cancelText: '取消',
          title: '确定删除阶段/类别?',
          onOk() {
            vm.loading =true
            view
              .removeWorkPack({ selectedWorkPackId: vm.selectRow.id })
              .then(({ code }) => {
                if (code === 200) {
                  vm.$message.success('删除成功')
                  row.operation = ''
                  vm.selectRow.operation = ''
                  vm.loadData()
                }
              })
              .finally(() => {
                vm.loading = false
              })
          }
        })
      } else {
        // 删除业务事项
        this.$confirm({
          okText: '确定',
          cancelText: '取消',
          title: '确定删除业务事项?',
          onOk() {
            vm.loading =true
            view
              .removeWork({ selectedWorkId: vm.selectRow.id })
              .then(({ code }) => {
                if (code === 200) {
                  vm.$message.success('删除成功')
                  row.operation = ''
                  vm.selectRow.operation = ''
                  vm.loadData()
                }
              })
              .finally(() => {
                vm.loading = false
              })
          }
        })
      }
    },
    /**
     * @description: 取消操作
     * @param {object} row 行数据
     * @return {void}
     */
    handleCancel(row) {
      this.selectRow.operation = ''
      for (let item in this.selectRow) {
        if (typeof this.selectRow[item] === 'object') {
          row[item] = this.selectRow[item] ? this.$clone(this.selectRow[item]) : null
        } else {
          row[item] = this.selectRow[item]
        }
      }
    },
    /**
     * @description: 手动刷新
     * @return {void}
     */    
    handleRefresh(){
      this.selectRow = {}
      this.currentRowKey = ''
      this.loadData()
    },
    /**
     * @description: 历史调整信息
     * @param {object} row 行数据
     * @return {void}
     */
    handleHistory(row) {
      this.historyAdjustVisible = true
      this.historyAdjustData = row
    },
    /**
     * @description: 提交校验预调整,有正在信息调整或删除的行返回false
     * @return {boolean}
     */    
    submitVerify(){
      return this.selectRow?.operation === undefined
    }
    // /**
    //  * @description: 校验树阶段/类别必须包含业务事项
    //  * @param {object} tree 数据树
    //  * @return {boolean}
    //  */
    // treeVerify(tree){
    //   let is = true
    //   const fun = (tree) => {
    //     for(let i = 0; i < tree.length; i ++){
    //       if(!is) break
    //       if(!Array.isArray(tree[i].childTree) || tree[i].childTree.length === 0){
    //         if(tree[i].nodeType === 0){
    //           is = false
    //         }
    //       }else{
    //         fun(tree[i].childTree)
    //       }
    //     }
    //   }
    //   fun(tree)
    //   return is
    // }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.preset-adjust {
  margin-bottom: 10px;
}
.btn-wrapper {
  margin: 0 -5px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  button {
    margin: 5px;
  }
}
.pub-table-select-count {
  margin-top: 5px;
  > span {
    margin-right: 12px;
  }
}
.sort-num {
  display: block;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  img {
    margin-right: 5px;
    width: 16px;
    height: 16px;
  }
}
.class-0 {
  // background-color: #d1d1d1;
  color: #606266;
}
.class-1 {
  color: #606266;
}
.class-2 {
  background-color: #f85c62;
}
.class-3 {
  background-color: #1dc682;
}
.class-4 {
  background-color: #ffced0;
}
.width-100 {
  width: 100%;
}
@{deep} .construction-schedule-view-table .el-table td .cell {
  overflow: visible;
}
.span-ellipsis {
  width: 100%;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}
.span-btn-ellipsis {
  width: 100%;
  display: flex;
  justify-content: center;
}
.span-btn-ellipsis-text {
  width: calc(100% - 85px);
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}
.span-btn-ellipsis-btn {
  width: 75px;
  margin-left: 10px;
}
</style>

